package com.moli.iov.open.authentication;

import com.moli.iov.open.authentication.domain.TokenResDto;
import com.moli.iov.open.authentication.store.TokenStore;
import com.moli.iov.open.constants.Constant;
import com.moli.iov.open.model.vo.req.ClientDetailsVo;
import com.moli.iov.rest.RestResponse;
import com.moli.iov.sys.model.dto.req.ClientDetailsReqDto;
import com.moli.iov.sys.model.dto.res.ClientDetailsResDto;
import com.moli.iov.sys.remote.IClientDetailsRemoteService;
import com.moli.iov.util.CommonUtils;
import com.moli.iov.util.TokenUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * <p>
 *
 * </p>
 *
 * @author zql
 * @since 2019/8/29 17:39
 */
@Component
public class TokenServices {

  @Autowired
  private TokenStore tokenStore;

  @Reference(group = "${service.group}", check = false)
  private IClientDetailsRemoteService clientDetailsRemoteService;

  /**
   * 获取access_token
   * @param clientDetailsVo
   * @return
   */
  public RestResponse token(ClientDetailsVo clientDetailsVo){

    // 根据 appID 获取客户信息
    RestResponse<ClientDetailsResDto> restResponse =
        clientDetailsRemoteService.getClientDetails(convert(clientDetailsVo));

    if(!restResponse.flag){
      return restResponse;
    }
    ClientDetailsResDto clientDetailsResDto = restResponse.getData();

    // 生成access_token
    String accessToken = TokenUtil.createUUID();

    // 存储access_token
    tokenStore.modifyAccessToken(accessToken, clientDetailsResDto);

    return RestResponse.success(new TokenResDto(accessToken, Constant.EXPIRES_IN));
  }

  /**
   *
   * 校验AccessToken是否存在 并返回客户端信息
   *
   * @param accessToken
   * @return
   */
  public ClientDetailsResDto validAccessToken(String accessToken){
    return tokenStore.validAccessToken(accessToken);
  }

  private ClientDetailsReqDto convert(ClientDetailsVo clientDetailsVo){
    ClientDetailsReqDto clientDetailsReqDto = new ClientDetailsReqDto();
    CommonUtils.copyProperties(clientDetailsVo, clientDetailsReqDto);
    return clientDetailsReqDto;
  }
}

